package com.boot.main.controller;

import cn.hutool.json.JSONUtil;
import com.boot.main.config.WxConfig;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.*;
import com.boot.main.utils.WxPayUtil;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@RequestMapping("/v1/weixin")
@Api(tags = "微信模块")
public class WxController {
    @Resource
    private ICityService cityService;
    @Resource
    private IAdService adService;
    @Resource
    private ICategoryService categoryService;
    @Resource
    private IProductService productService;
    @Resource
    private IShopService shopService;
    private RSAAutoCertificateConfig config;
    private NotificationConfig noticeConfig;
//    @Autowired
    public void setConfig(){
        config = new RSAAutoCertificateConfig.Builder()
                .merchantId(WxConfig.merchartId)
                .privateKeyFromPath(WxConfig.privateKeyPath)
                .merchantSerialNumber(WxConfig.merchantSerialNumber)
                .apiV3Key(WxConfig.apiV3key)
                .build();
        noticeConfig = new RSAAutoCertificateConfig.Builder()
                .merchantId(WxConfig.merchartId)
                .privateKeyFromPath(WxConfig.privateKeyPath)
                .merchantSerialNumber(WxConfig.merchantSerialNumber)
                .apiV3Key(WxConfig.apiV3key)
                .build();
    }

    @RequestMapping(value="/jscode2session", method = RequestMethod.GET)
    @ApiOperation(value = "微信登录")
    public Object jscode2session(@RequestParam("code") String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx93f5d66572e98eca&secret=9517cb3de6a4350faa73916ca2e2b0db&js_code="+code+"&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
        Object data = JSONUtil.parse(entity.getBody());
        return ResponseDataUtil.success("获取数据成功", data);
    }

    @RequestMapping(value="/prePay", method = RequestMethod.POST)
    @ApiOperation(value="微信预支付")
    public Object prePay(@RequestBody String openId,
                         @RequestBody String number,
                         @RequestBody Integer saleNum,
                         @RequestBody String desc) throws FileNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Date now = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String t1 = sdf1.format(now);
        String order_no = t1 + number;
        JsapiService service = new JsapiService.Builder().config(config).build();
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(saleNum);
        request.setAmount(amount);
        request.setAppid(WxConfig.appid);
        request.setMchid(WxConfig.merchartId);
        request.setDescription(desc);
        request.setNotifyUrl("");
        request.setOutTradeNo(order_no);
        Payer payer = new Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        PrepayResponse response = service.prepay(request);
        String prepayId = response.getPrepayId();
        String nonceStr = WxPayUtil.generateNonceStr();
        long timeStamp = WxPayUtil.getCurrentTimestamp();
        String prepayidstr = "prepay_id=" + prepayId;
        String signType = "RSA";
        String signatureStr = Stream.of(WxConfig.appid, String.valueOf(timeStamp), nonceStr, prepayidstr).collect(Collectors.joining("\n", "", "\n"));
        String paySign = WxPayUtil.getSign(signatureStr);
        HashMap map = new HashMap();
        map.put("code", 200);
        map.put("appId", WxConfig.appid);
        map.put("timeStamp", String.valueOf(timeStamp));
        map.put("nonceStr", nonceStr);
        map.put("package", prepayidstr);
        map.put("signType", signType);
        map.put("paySign", paySign);
        map.put("openid", openId);
        return ResponseDataUtil.success("获取数据成功", map);
    }

    @RequestMapping(value="/wxPayNotice", method = RequestMethod.POST)
    @ApiOperation(value="微信支付回调")
    public Object WxPayNotice(@RequestHeader("Wechatpay-Seria") String wechatPayCertificateSerialNumber,
                              @RequestHeader("Wechatpay-Signature") String signature,
                              @RequestHeader("Wechatpay-Timestamp") String timestamp,
                              @RequestHeader("Wechatpay-Nonce") String nonce,
                              @RequestBody String requestBody){
        com.wechat.pay.java.core.notification.RequestParam requestParam = new com.wechat.pay.java.core.notification.RequestParam.Builder()
                .serialNumber(wechatPayCertificateSerialNumber)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(requestBody)
                .build();
        NotificationParser parser = new NotificationParser(config);
        Object decryptObject = parser.parse(requestParam, Object.class);
        Object data = JSONUtil.parse(requestBody);
        return ResponseDataUtil.success("获取数据成功", null);
    }

    @RequestMapping(value = "/city", method = RequestMethod.GET)
    @ApiOperation(value = "获取城市列表")
    public Object getCity(){
        return cityService.getCity();
    }

    @RequestMapping(value = "/ads", method = RequestMethod.GET)
    @ApiOperation(value = "获取banner列表")
    public Object getAds(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, @RequestParam("name") String name){
        return adService.getAdminAds(page, limit, name);
    }

    @RequestMapping(value="/categorys", method = RequestMethod.GET)
    @ApiOperation(value="获取分类列表")
    public Object getCategorys(){
        return categoryService.getAdminCategorys();
    }

    @RequestMapping(value="/category/{status}", method = RequestMethod.GET)
    @ApiOperation(value = "获取推荐分类")
    public Object getCategoryByStatus(@PathVariable("status") Integer status){
        return categoryService.getAdminCategoryByStatus(status);
    }

    @RequestMapping(value="/shops", method = RequestMethod.GET)
    @ApiOperation(value="获取店铺列表")
    public Object getShops(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit, @RequestParam("name") String name){
        return shopService.getAdminShops(page, limit, name);
    }

    // https://market.aliyun.com/products/57124001/cmapi022273.html?spm=5176.10695662.1996646101.searchclickresult.33a042abItJN4Q#sku=yuncode1627300000
    // http://127.0.0.1:8081/v1/weixin/logistics?no=78754552286771&type=
    @RequestMapping(value="/logistics", method = RequestMethod.GET)
    @ApiOperation(value = "查询物流")
    public Object getLogistics(@RequestParam("no") String no, @RequestParam("type") String type){
        String url = "https://kdwlcxf.market.alicloudapi.com/kdwlcx?no="+no+"&type="+type;
        String appcode = "7f9f446bd06d49048f069b12c24fe95a";
        String authorization = "APPCODE " + appcode;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", authorization);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        Object data = JSONUtil.parse(entity.getBody());
        return ResponseDataUtil.success("获取数据成功", data);
    }
}
